package semantic_compute.relation_extraction.yago_matcher;

import common.dao.postgre.PostGreJDBCDao;
import knowlwdge_graph.knowledge_etl.yago_etl.ExtractorPostgres;
import knowlwdge_graph.knowledge_etl.yago_etl.RowYagoTriple;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by julianzliu on 4/23/2017.
 */
public class ExtractorFromPostgres {

    static final org.slf4j.Logger logger = LoggerFactory.getLogger(ExtractorFromPostgres.class);

    private PostGreJDBCDao postGreJDBCDao;
    private Connection conn;

    public ExtractorFromPostgres(){
        this.postGreJDBCDao = new PostGreJDBCDao();

        this.conn = this.postGreJDBCDao.getConn();

        if(this.conn == null){
            logger.error("[ExtractorFromPostgres] Connection Failed!!!\n\n");
        }
    }


    public List<RowYagoTriple> getRelatonGloss(String subject){
        String sql = String.format("select * from yagofacts where subject='%s' and predicate='%s';", subject, "<hasGloss>" );

        logger.info("[getPartitialRowSet] sql = \n{}", sql);

        Statement stmt=null;
        ResultSet rs=null;
        List<RowYagoTriple> rows = new ArrayList<>();
        try
        {
            stmt=this.conn.createStatement();
            rs=stmt.executeQuery(sql);
            while(rs.next()){
                rows.add(
                        new RowYagoTriple(
                                rs.getString(1),//("id"),
                                rs.getString(2),//("subject"),
                                rs.getString(3),//("predicate"),
                                rs.getString(4).replace("'","\\'"),//("object"),
                                rs.getFloat(5)//("value")
                        )
                );
            }
            rs.close();
            stmt.close();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        return rows;
    }

}
